<?php

namespace app\core\util;

use app\core\Util;

/**
 * @extends Util<Tree>
 */
class Tree extends Util
{
    public function buildTree(array $arr, $index = 0, $id_name = 'id', $parent_id_name = 'parent_id')
    {
        $tree = $this->findChild($arr, $index, $parent_id_name);

        if (count($tree) <= 0) {
            return [];
        }

        foreach ($tree as $k => $menu) {
            $child = $this->buildTree($arr, $menu[$id_name], $id_name, $parent_id_name);
            if (count($child) > 0) {
                $tree[$k]['children'] = $child;
            }
        }

        return $tree;
    }

    public function findChild(array $arr, $pid, $parent_id_name = 'parent_id')
    {

        $child = [];
        foreach ($arr as $menu) {
            if ($menu[$parent_id_name] == $pid) {
                $child[] = $menu;
            }
        }
        return $child;
    }
}